package jml.defaultimple.web;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jml.config.Config;
import jml.config.Descriptor;
import jml.defaultimple.util.UFile;

public class ServletStar extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		// path del disco
		String path = request.getParameter("path");
		
		// nombre del star
		String starName = request.getParameter("starName");
		
		// true=>starred; false=>untarred
		boolean mark = request.getParameter("mark").equals("true");
				
		// ahora debo editar el .properties
		//String fileToEdit = UFile.getFiles(path, Config.getConfig(false).getDescriptor().getFileExtension())[0];
		Descriptor d = Config.getConfig(false).getDescriptor();
		String fileToEdit = d.getDescriptorFilename(path);
		
		
		_agregarProperty(path+"\\"+fileToEdit,starName,mark);
	}

	private void _agregarProperty(String fileToEdit, String starName, boolean mark)
	{
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try
		{
			// abro las properties
			fis = new FileInputStream(fileToEdit);
			Properties p = new Properties();
			p.load(fis);
			
			fos = new FileOutputStream(fileToEdit);
			
			p.setProperty(starName, mark?"true":"false");
			
			p.store(fos, "---NO TOCAR---");
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		finally
		{
			try
			{
				if(fos!=null) fos.close();
				if(fis!=null) fis.close();
			}
			catch(Exception e2)
			{
				e2.printStackTrace();
				throw new RuntimeException(e2);
			}
		}
	}
}
